package com.cellulam.framework.fs.common;

import com.google.common.collect.Lists;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
public class DataTable {

    private static final DateTimeFormatter dtf_dt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter dtf_d = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dtf_t = DateTimeFormatter.ofPattern("HH:mm:ss");

    /**
     * 第一行, 标题
     */
    private List<String> headers = Lists.newArrayList();

    /**
     * 数据行(s)
     */
    private List<List<String>> dataRows = Lists.newArrayList();

    /**
     * 添加标题
     * @param header
     */
    public void addHeader(String header) {
        headers.add(header);
    }

    /**
     * 添加标题, 指定下标
     * @param index
     * @param header
     */
    public void addHeader(int index, String header) {
        headers.add(index, header);
    }

    /**
     * 增加一行数据
     * @param values
     */
    public void addRow(List<Object> values) {
        dataRows.add(values.stream().map(this::valueToText).collect(Collectors.toList()));
    }

    private String valueToText(Object value) {
        if (value == null) {
            return "";
        }
        if (value instanceof Number) {
            DecimalFormat df = new DecimalFormat("###########.####");
            return df.format((Number) value);
        } else if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format((Date) value);
        } else if (value instanceof LocalDateTime) {
            return ((LocalDateTime) value).format(dtf_dt);
        } else if (value instanceof LocalDate) {
            return ((LocalDate) value).format(dtf_d);
        } else if (value instanceof LocalTime) {
            return ((LocalTime) value).format(dtf_t);
        }

        return String.valueOf(value);
    }

    public List<String> getHeaders() {
        return headers;
    }

    public void setHeaders(List<String> headers) {
        this.headers = headers;
    }

    public List<List<String>> getDataRows() {
        return dataRows;
    }

    public void setDataRows(List<List<String>> dataRows) {
        this.dataRows = dataRows;
    }
}
